package com.ruoyi.quartz.task;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.cs.domain.*;
import com.ruoyi.cs.domain.dto.battle.BattleStartReq;
import com.ruoyi.cs.domain.vo.TBackPackVo;
import com.ruoyi.cs.domain.vo.TbattleCreateVo;
import com.ruoyi.cs.mapper.*;
import com.ruoyi.cs.service.*;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.cs.service.ITRollService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Component("ryTask")
@SuppressWarnings("all")
public class RyTask
{
    private static final Logger log = LoggerFactory.getLogger(RyTask.class);
    @Autowired
    private ITRollService trollService;
    @Autowired
    private TRollMapper tRollMapper;
    @Autowired
    private TRechargeMapper tRechargeMapper;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private TRollCyMapper tRollCyMapper;
    @Autowired
    private TBackpackMapper tBackpackMapper;
    @Autowired
    private CommonService commonService;
    @Autowired
    private TBackpackOperateMapper tBackpackOperateMapper;
    @Autowired
    private TBattleInfoMapper tBattleInfoMapper;
    @Autowired
    private ITBattleInfoService tBattleInfoService;
    @Autowired
    private IRechargeTaskService rechargeTaskService;
    @Autowired
    private ITUserService tUserService;
    @Autowired
    private ISysDictTypeService sysDictTypeService;
    @Autowired
    private TBoxMapper tBoxMapper;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private ITFringeBenefitsService itFringeBenefitsService;
    @Autowired
    private ITBankcardBehalfpayService bankcardBehalfpayService;
    @Autowired
    private ITVipGradeService itVipGradeService;
    @Autowired
    private TUserMapper tUserMapper;
    @Autowired
    private ITBackpackService tBackpackService;
    /**
     * ROLL房定时自动开奖
     */
    public void automaticLottery(){
        List<TRoll> list = tRollMapper.manchuOrAutoLotteryRollList();
        int count = 0;
        if (list.size() > 0) {
            for (TRoll tRoll : list) {
                try {
                    if (tRoll.getRollZdkjTime().compareTo(new Date()) <= 0){
                        trollService.automaticLotteryHash(tRoll);
                        log.info(tRoll.getRollName() + ": ROLL房定时开奖成功");
                        count++;
                    }else  if("1".equals(tRoll.getDrawPriceType())){
                        Map<String,Long> map = tRollCyMapper.countUserNumByRollId(tRoll.getRollId());
                        Long userNum = map.get("userNum");
                        if (userNum>=Long.parseLong(tRoll.getCyNumberlimit())){
                            trollService.automaticLotteryHash(tRoll);
                            log.info(tRoll.getRollName() + ": ROLL房满人开奖定时开奖成功");
                            count++;
                        }else {
                            log.info(tRoll.getRollName() + ": ROLL房参与人数不足，达不到开奖要求");
                        }
                    }
                } catch (Exception e) {
                    log.error(tRoll.getRollName() + ": ROLL房定时自动开奖异常，ROLLID:{},异常信息:{}",tRoll.getRollId(),e.getMessage());
                }
            }
            log.info("ROLL房定时开奖，查询个数:{}，开奖个数:{}",list.size(),count);
        }else {
            log.info("定时扫描无需要开奖的ROLL房");
        }
    }


    /**充值订单轮询*/
    public void expireTRecharge(Integer pollingNum,Integer minute) {
        String time =  DateUtils.getPastDateMinute(minute);
        List<TRecharge> list = tRechargeMapper.paymentListToBeConfirmed(Constants.CZSTATUS0, null, time);
        log.info("支付定时处理订单个数:{}", list == null ? 0 : list.size());
        if (!CollectionUtils.isEmpty(list)) {
            /**yukuaiqi*/
            List<TRecharge> yukuaiqiList = list.stream().filter(bean -> bean.getCzPlatform().equals(Constants.CZPLATFORM7)).collect(Collectors.toList());
            rechargeTaskService.expireYukuaiqiRecharge(yukuaiqiList, pollingNum);

            /**sanjin*/
            List<TRecharge> sanjinList = list.stream().filter(bean -> bean.getCzPlatform().equals(Constants.CZPLATFORM8)).collect(Collectors.toList());
            rechargeTaskService.expireSanjinRecharge(sanjinList, pollingNum);
        }
    }
    /**
     * 定时扫描，对饰品取货超时20分钟后的数据进行6次轮询确认状态
     */
    public void expriceGoodsDd24() {
        List<TBackpack> list = tBackpackMapper.getExpriceListMax();
        if (list.size() > 0) {
            for (TBackpack tBackpack : list) {
                tBackpack.setFailNum(tBackpack.getFailNum() == null ? 1 : tBackpack.getFailNum() + 1);
                if (StringUtils.isNotEmpty(tBackpack.getOperateId())) {
                    String body = commonService.qureySteamOrderYY(tBackpack.getOperateId());
                    JSONObject jsonObject = JSON.parseObject(body);
                    if (jsonObject.getInteger("code") == 0) {
                        Integer bigStatus = jsonObject.getJSONObject("data").getInteger("bigStatus");
                        String statusMsg = jsonObject.getJSONObject("data").getString("statusMsg");

                        if (bigStatus == 340) {
                            commonService.updateBackPolling(tBackpack, "10", "2",statusMsg);
                        } else if (bigStatus == 280) {
                            commonService.updateBackPolling(tBackpack, "11", "2",statusMsg);
                        }
                    } else {
                        String msg = jsonObject.getString("msg");
                        commonService.updateBackPolling(tBackpack, "polling", "2",msg);
                    }
                }
            }
        }
    }

    /**
     * 交易失败的饰品轮询，初始化状态
     */
    public void dealFailed() {
        try {
            List<TBackPackVo> list = tBackpackMapper.getDealFailedList();
            if (list.size() > 0) {
                tBackpackService.dealFailed(list);;
            }
            log.info("定时初始化交易失败饰品：{}条", list.size());
        } catch (Exception e) {
            log.error("交易失败的饰品轮询，初始化状态异常:{}",e);
        }
    }


    /**超时48小时未有人参与的对战房间进行过期处理*/
    public void obsoleteBattle(Integer hour){
        List<TBattleInfo> list = tBattleInfoMapper.obsoleteBattleList(hour);
        if (list.size() > 0) {
            int row = 0;
            for (TBattleInfo tBattleInfo : list) {
                try {
                    tBattleInfoService.obsoleteBattle(tBattleInfo);
                    row++;
                } catch (Exception e) {
                    log.error("对战房间 {}:过期处理失败，原因：{}",tBattleInfo.getBattleId(),e.getMessage());
                }
            }
            log.info("成功处理对战房间过期数据：{}条",row);
        }else {
            log.info("对战房间无过期处理！");
        }
    }

    /**自动修改对战间状态*/
    @Transactional
    public void battleOver(){
        List<TBattleInfo> battleList = tBattleInfoMapper.selectAminuteAgo();
        if (battleList.size() > 0) {
            Map<String, String> battleMap = battleList.stream().collect(Collectors.toMap(TBattleInfo::getBattleId,TBattleInfo::getBattleType));
            List<String> battleIdList = battleList.stream().map(TBattleInfo::getBattleId).collect(Collectors.toList());
            int i = tBattleInfoMapper.updateBattleInfoStatus(battleIdList);
            if(i > 0){
                log.info("定时修改对战间状态成功：{}条",battleIdList.size());
            }
        }else {
            log.info("指定时间内无对战中的对战间！");
        }
    }

    /**
     * 对战机器人余额定时重置
     */
    public void battleRobotBalanceRecover(){
        try {
            tUserService.battleRobotBalanceRecover();
        }catch (Exception e){
            log.error("机器人余额重置失败：{}",e.getMessage());
        }
    }

    /**
     * 主播禁止取回时取回数据处理
     */
    public void anchorRetrievalDispose(){
        List<TBackpack> list = tBackpackMapper.anchorRetrievalDispose();
        if(list.size()>0){
            for (TBackpack tBackpack: list){
                tBackpack.setBbStatus(Constants.BBSTATUS2);
                tBackpack.setArrivalTime(DateUtils.getNowDate());
                tBackpack.setUpdateTime(DateUtils.getNowDate());
                tBackpack.setErrormsg("已完成交易");
            }
            int row = tBackpackMapper.updateAnchorRetrieval(list);
            log.info("主播背包取回数据需要处理：{}条，成功处理条数：{}条", list.size(), row);
        }else {
            log.info("定时扫描无需要处理的主播订单！");
        }
    }

    /**
     * 创建AI对战
     */
    public void createAIBattle() {
        /*查询出当前不存在的ai对战间类型*/
        List<SysDictData> costRangeTypeList = sysDictTypeService.selectDictDataByType("cost_range_type");
        if (!CollectionUtils.isEmpty(costRangeTypeList)) {
            List<String> list = costRangeTypeList.stream().map(data -> data.getDictLabel()).collect(Collectors.toList());
            /*查询当前等待中状态的ai对战间*/
            List<TBattleInfo> aiTBattleInfoList = tBattleInfoMapper.selectAIBattleInfo(null,null);
            if (!CollectionUtils.isEmpty(aiTBattleInfoList)) {
                /*筛选出不存在的对战间等级类型*/
                costRangeTypeList = costRangeTypeList.stream()
                        .filter(notExist -> !aiTBattleInfoList.stream().map(all -> all.getCostRangeType()).collect(Collectors.toList()).contains(notExist.getDictLabel()))
                        .collect(Collectors.toList());
            }
            if (!CollectionUtils.isEmpty(costRangeTypeList)) {
                /*查询出字典中最高对战间价格所属区间类型*/
                String minPrice = "0";
                String maxPrice = "0";
                SysDictData maxSysData = costRangeTypeList.stream().filter(Objects::nonNull).max(Comparator.comparing(SysDictData::getDictLabel)).get();
                String maxDictValue = maxSysData.getDictValue();
                String[] maxPriceArr = maxDictValue.split(",");
                if (maxPriceArr.length > 0) {
                    maxPrice = maxPriceArr[maxPriceArr.length - 1];
                }
                SysDictData minSysData = costRangeTypeList.stream().filter(Objects::nonNull).min(Comparator.comparing(SysDictData::getDictLabel)).get();
                String minDictValue = minSysData.getDictValue();
                String[] minPriceArr = minDictValue.split(",");
                if (minPriceArr.length > 0) {
                    minPrice = minPriceArr[0];
                }
                List<TBox> battleBoxList = tBoxMapper.selectBattleBoxByPrice(maxPrice);
                /*查询出价格区间的箱子*/
                if (!CollectionUtils.isEmpty(battleBoxList)) {
                    for (SysDictData sysDictData : costRangeTypeList) {
                        /*根据价格类型区间过滤箱子*/
                        String dictValue = sysDictData.getDictValue();
                        String[] split = dictValue.split(",");
                        List<TBox> tBoxFilter = null;
                        /*箱子最高价格*/
                        BigDecimal boxMaxPrice = new BigDecimal(0);
                        /*计算后的箱子最高价格*/
                        BigDecimal boxoptionalPrice = new BigDecimal(0);
                        if (split.length > 0) {
                            boxMaxPrice = new BigDecimal(split[split.length - 1]);
                            tBoxFilter = battleBoxList.stream().filter(tbox -> tbox.getBoxPrice().compareTo(new BigDecimal(split[0])) > 0 && tbox.getBoxPrice().compareTo(new BigDecimal(split[split.length - 1])) <= 0).collect(Collectors.toList());
                        }
                        if (!CollectionUtils.isEmpty(tBoxFilter)) {
                            /*选中的箱子*/
                            List<TBox> checkedBoxList = new ArrayList<>();
                            /*选中的箱子价格*/
                            BigDecimal price = new BigDecimal(0);
                            Random random = new Random();
                            int index = random.nextInt(tBoxFilter.size());
                            TBox tBox = tBoxFilter.get(index);
                            price = price.add(tBox.getBoxPrice());
                            boxoptionalPrice = boxMaxPrice.subtract(price);
                            checkedBoxList.add(tBox);
                            for (int i = 0; i < 5; i++) {
                                /*重新过滤*/
                                //tBoxFilter = battleBoxList.stream().filter(tbox -> tbox.getBoxPrice().compareTo(new BigDecimal(split[split.length - 1])) <= 0).collect(Collectors.toList());

                                List<TBox> tBoxFilter1 = new ArrayList<>();
                                if (checkedBoxList.size() < 5 && price.compareTo(boxMaxPrice) < 0) {
                                    /*过滤出箱子价格小于类型最高价-已选箱子价格差的箱子*/
                                    for (TBox tBox1 : battleBoxList) {
                                        if (tBox1.getBoxPrice().compareTo(boxoptionalPrice) < 0) {
                                            tBoxFilter1.add(tBox1);
                                        }
                                    }
                                    if (tBoxFilter1.size() > 0) {
                                        int index1 = random.nextInt(tBoxFilter1.size());
                                        TBox tBox1 = tBoxFilter1.get(index1);
                                        price = price.add(tBox1.getBoxPrice());
                                        if (price.compareTo(boxMaxPrice) < 0) {
                                            checkedBoxList.add(tBox1);
                                            price.add(tBox1.getBoxPrice());
                                            boxoptionalPrice = boxMaxPrice.subtract(price);
                                        } else {
                                            break;
                                        }
                                    } else {
                                        break;
                                    }
                                }
                            }
                            if (checkedBoxList.size() > 0) {
                                try {
                                    List<String> checkedBoxIdList = checkedBoxList.stream().map(be -> be.getBoxId()).collect(Collectors.toList());
                                    Collections.shuffle(checkedBoxIdList);
                                    BigDecimal sumBoxPrice = checkedBoxList.stream().map(TBox::getBoxPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
                                    /*随机获取金额大于当前对战房间花费金额的机器人*/
                                    List<TUser> tUserList = tUserService.selectBattleRobot(sumBoxPrice.toString());
                                    if (CollectionUtils.isEmpty(tUserList)) {
                                        //重置所有对战机器人金额
                                        tUserService.battleRobotBalanceRecover();
                                        tUserList = tUserService.selectBattleRobot(sumBoxPrice.toString());
                                    }
                                    /*如果重置完后机器人还是为空则认为当前根本不存在对战机器人*/
                                    if (!CollectionUtils.isEmpty(tUserList)) {
                                        TUser tUser = tUserList.get(random.nextInt(tUserList.size()));
                                        /*调用创建方法创建对战房间*/
                                        TbattleCreateVo tbattleCreateVo = new TbattleCreateVo();
                                        tbattleCreateVo.setBoxs(checkedBoxIdList);
                                        tbattleCreateVo.setCostRangeType(sysDictData.getDictLabel());
                                        Integer random_number = RandomUtil.randomInt(2, 5); // 区间是 [2, 5)，左闭右开
                                        tbattleCreateVo.setBattleNum(random_number.toString());
                                        tbattleCreateVo.setBattleMode("0");
                                        tBattleInfoService.createBattle(tUser.getUserId(), tbattleCreateVo);
                                        log.info("选择的箱子数量：{},区间：{},箱子ID：{}", checkedBoxList.size(), dictValue, checkedBoxIdList);
                                    } else {
                                        log.info("当前不存在对战机器人");
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    log.info("创建AI对战房间失败：{}", e.getMessage());
                                }
                            }
                        } else {
                            log.info("不存在当前价格区间的箱子：{}", dictValue);
                        }
                    }
                } else {
                    log.info("不存在当前档位区间的箱子,最低价：{},最高价：{}", minPrice, maxPrice);
                }
            } else {
                log.info("无需创建AI对战，全部价格区间类型都已存在");
            }
        } else {
            log.info("无需创建AI对战，不存在AI对战间价格区间类型");
        }
    }

//    /**
//     * 测试机器人参与AI对战
//     */
//    public void testRobotstartAIBattle() {
//        /*获取机器人参与限制*/
//        SysConfig robotAIBattleLimitConfig = sysConfigMapper.checkConfigKeyUnique("testRobot_joinAIBattle_limit");
//        String robotAIBattleLimit = robotAIBattleLimitConfig == null || StringUtils.isEmpty(robotAIBattleLimitConfig.getConfigValue()) ? "5" : robotAIBattleLimitConfig.getConfigValue();
//        /*查询出测试账号可以参与的对战房间*/
//        List<TBattleInfo> tBattleInfoList = tBattleInfoMapper.selectAIBattleInfo(robotAIBattleLimit, null);
//        if (!CollectionUtils.isEmpty(tBattleInfoList)) {
//            try {
//                /*获取测试账号*/
//                TUser tUserParam = new TUser();
//                tUserParam.setUserType(Constants.USERTYPE4);
//                tUserParam.setDelFlag(Constants.SUCCESS);
//                List<TUser> tUsers = tUserService.selectUserList(tUserParam);
//                Random random = new Random();
//                int num = 0;
//                if (!CollectionUtils.isEmpty(tUsers)) {
//                    /*循环所有对战房间，随机测试账号参与*/
//                    for (TBattleInfo tBattleInfo : tBattleInfoList) {
//                        int i = random.nextInt(tUsers.size());
//                        TUser tUser = tUsers.get(i);
//                        /*随机获取5-10分钟*/
//                        int minute = new Random().nextInt(6) + 5;
//                        Long gqtime = DateUtils.getPastDateMinuteLong(minute);
//                        if(tBattleInfo.getCreateTime().getTime() <= gqtime){
//                            BattleStartReq battleStartReq = new BattleStartReq();
//                            battleStartReq.setBattleId(tBattleInfo.getBattleId());
//                            battleStartReq.setChooseRobot(false);
//                            tBattleInfoService.startBattleV2(battleStartReq, tUser.getUserId());
//                        }
//                        num++;
//                    }
//                    log.info("测试账号参与AI对战房间成功，数量：{}",num);
//                } else {
//                    log.info("未找到符合条件的测试账号");
//                }
//            } catch (Exception e) {
//                log.error("测试账号参与对战房间异常：{}", e.getMessage());
//            }
//        } else {
//            log.info("未找到符合测试账号参与条件的AI对战房间,等级限制：{},当前时间：{}", robotAIBattleLimit, DateUtils.getTime());
//        }
//    }

//    /**
//     * 每日福利自动领取
//     */
//    public void dailyBeneFitsAutoReceive(){
//        try {
//            itFringeBenefitsService.dailyBeneFitsAutoReceive();
//        }catch (Exception e){
//            log.error("定时自动领取每日福利异常：{}",e.getMessage());
//        }
//    }

//
//    /**
//     * 宝和利代付订单定时处理
//     */
//    public void bhlbehalfpayHandle(){
//        List<TBankcardBehalfpay> list = bankcardBehalfpayService.selectTBankcardBehalfpayAll();
//        int count=0;
//        if (list != null && list.size() > 0){
//            for (TBankcardBehalfpay bankcardBehalfpay : list) {
//                bankcardBehalfpayService.bhlbehalfpayHandle(bankcardBehalfpay);
//                count++;
//            }
//        }
//        log.info("宝和利代付订单处理完成，条数:{}",count);
//    }

//    /**
//     * VIP会员30天内未进行等级变动的进行保级或者降级定时处理
//     */
//    public void vipUserHandle(){
//        List<Map> list = itVipGradeService.allVipUserExpire();
//        int successCount=0;
//        int failCount = 0;
//        if (list != null && list.size() > 0){
//            List<TVipGrade> tVipGradeList = itVipGradeService.vipList();
//            for (Map map : list) {
//                String userId = map.get("userId").toString();
//                try {
//                    itVipGradeService.VipExpire(userId,tVipGradeList);
//                    successCount++;
//                } catch (Exception e) {
//                    failCount++;
//                    log.error("IP会员30天内未进行等级变动的进行保级或者降级处理失败ID：{},异常:{}",userId,e.getMessage());
//                }
//            }
//        }
//        log.info("IP会员30天内未进行等级变动处理总条数:{}，成功处理:{},失败处理:{}",list.size(),successCount,failCount);
//    }

    /**
     * @Desc: 每天凌晨n点，减去头像框时长一天
     * @author: zz
     * @date: 2024/3/25
     */
    public void subAvatarFrameDuration(){
        tUserMapper.subAvatarFrameDuration();
    }
}
